﻿@using System.Web.Script.Serialization
@using MvcApplication1.Models

@{
    Layout = "~/Views/Shared/_contentLayout.cshtml";
}

<style>
    #sceneArrangePanel
    {
        width: 800px;
        height: 600px;
        overflow: scroll;
    }
    .activeScene
    {
        background-color: Blue;
    }
    .title
    {
        font-size: 20pt;
        font-weight: bold;
        cursor: pointer;
    }
    .titleInstructions
    {
        font-size: 8pt;
        font-style: italic;
    }
    #sceneSelectorSection
    {
        white-space: nowrap;
        float: left;
        cursor: pointer;
        height: 100px;
        width: 400px;
        overflow: auto;
        overflow-y: hidden;
    }
    .storyMenu
    {
        float: left;
    }
    .sceneSelector
    {
        border: 1px solid black;
        display: inline-block;
        width: 70px;
        height: 70px;
        text-align: center;
        vertical-align: middle;
        margin: 4px;
    }
</style>

<script>
    var story = @Html.Raw(new JavaScriptSerializer().Serialize(Model))
    var uiInfo = {currentSceneIndex: null};

    function compareScenes(a, b) {
        return a.Order > b.Order ? 1 : -1;
    }

    function handlePlaceholderKeyup() {
        if ($('#newScenePlaceholderTextarea').val().length == 0) return;
        addSceneToUI(newScene());
    }

    function addPlaceholderScene(scene) {
        $('#newScenePlaceholderTextarea').unbind();

        if (scene.Name) $('#newScenePlaceholderTextarea').val(scene.Name);
        $('#newScenePlaceholder .sceneArrangeTitle').text('');
        $('#newScenePlaceholderTextarea').change(function(event){story.Scenes[scene.Order].Name = $(event.target).val();});

        $('#newScenePlaceholder').attr('id', 'arrange_' + scene.Order);
        $('#newScenePlaceholderTextarea').attr('id', null);
        addNewScenePlaceholder();
    }

    function addNewScenePlaceholder() {
        $('#sceneArrangePanel').append($('<li id="newScenePlaceholder"><table><tr><td>[Move icon]</td><td><div class="sceneArrangeTitle">New Scene</div><textarea id="newScenePlaceholderTextarea" cols="50" rows="3"></textarea></td></tr></table></li>'));
        $('#newScenePlaceholderTextarea').keyup(handlePlaceholderKeyup);
    }

    function addSceneForEdit(scene) {
        $('<span class="sceneSelector" title="' + scene.Summary + '" id="scene_' + scene.Order + '">' + (scene.Order + 1) + '</span>').insertBefore($('#addSceneLink'));
        var target = $('#scene_' + scene.Order);
        target.click(function(event){selectScene(event.target)});
    }

    function addSceneToUI(scene) {
        addSceneForEdit(scene);
        addPlaceholderScene(scene);
    }

    function newScene() {
        var scene =  @Html.Raw(new JavaScriptSerializer().Serialize(new Scene()));
        scene.Id = 0;
        scene.Order = story.Scenes.length;
        story.Scenes[scene.Order] = scene;
        return scene;
    }

    function addSceneToCollection() {
        var scene = newScene();
        addSceneToUI(scene);
        selectScene($('#scene_' + scene.Order));
    }

    function selectScene(target) {
        var idValue = $(target).attr('id');
        if (idValue == 'addSceneLink') return;

        var index = idValue.replace('scene_', '');
        uiInfo.currentSceneIndex = index;
        var scene = story.Scenes[index];
        $('#sceneEditor').show();
        if (scene.Name) $('#sceneName').text(scene.Name);
        else $('#sceneName').text('<Scene ' + (scene.Order + 1) + '>');
        $('#sceneSummary').val(scene.Summary);
        $('#sceneProse').val(scene.Prose);

        $('.sceneSelector').removeClass('activeScene');
        $(target).addClass('activeScene');

        centerInDiv(scene);
    }

//there seems to be a chrome rendering bug with this
    function centerInDiv(scene) {
        /*var target = $('#scene_' + scene.Order).get(0);
        var parent = $('#scene_' + scene.Order).parent().get(0);
        var numberOfElements = window.parseInt(parent.offsetWidth / target.offsetWidth / 2);
        var minIndex = scene.Order - numberOfElements;
        if (minIndex < 0) minIndex = 0;
        var maxIndex = scene.Order + numberOfElements;
        if (maxIndex > story.Scenes.length - 1) maxIndex = story.Scenes.length - 1;

        $('#scene_' + maxIndex).get(0).scrollIntoView();
        $('#scene_' + minIndex).get(0).scrollIntoView();
        $('div').get(0).scrollIntoView();*/
    }

    function editTitle(target) {
        var oldValue = $(target).html();
        $(target).html('<input id="input_placeholder" value="' + oldValue + '"/>');
        $('#input_placeholder').blur(function(){
            var newValue = $('#input_placeholder').val();
            if (newValue.length == 0) newValue = oldValue;
            if ($(target).attr('id') == 'sceneName') {
                story.Scenes[uiInfo.currentSceneIndex].Name = newValue;
                $('#arrange_' + uiInfo.currentSceneIndex + ' textarea').val(newValue);
            }
            if ($(target).attr('id') == 'storyTitle') story.Title = newValue;
            $(target).html(newValue);
        });
        $('#input_placeholder').focus();
    }

    function save() {
        $.jsonSave('Save', story, function(newStory){story = newStory;});
    }

    function toggleSummary() {
        $('#summaryEditor').toggle();
    }

    jQuery.fn.selectFromGroup = function(selector) {
        $(this).hide();
        $(selector).show();
    };

    function sort(event, ui) {
        var id = $(event.srcElement).parentsUntil('ul').last().attr('id');
        if (id == 'newScenePlaceholder') return;

        var movedElement = $('#' + id);
        var newIndex = $(movedElement).parent().children().index(movedElement);

        //if an element is moved past the placeholder, move it to right before the placeholder
        if (newIndex == $('#sceneArrangePanel li').length - 1) {
            movedElement.remove();
            movedElement.insertBefore($('#sceneArrangePanel li').last());
            newIndex--;
        }

        var originalIndex = id.replace('arrange_', '');
        if (originalIndex == newIndex) return;

        var originalItem = story.Scenes[originalIndex]

        story.Scenes.splice(originalIndex, 1);
        story.Scenes.splice(newIndex, 0, originalItem);
        $(story.Scenes).each(function(index, scene) {
            scene.Order = index;
            $('#sceneArrangePanel li').eq(index).attr('id', 'arrange_' + index);
        });
    }

    function startDrag(event, ui) {
        var id = $(event.srcElement).parentsUntil('ul').last().attr('id');
        if (id == 'newScenePlaceholder') addSceneToUI(newScene());
    }

    function showSceneEditor() {
        $('#sceneEditor').hide();
        $('.editPanel').selectFromGroup('#sceneArrangePanel');
    }

    $(function() {
        $('#modeMenu').modeButton();

        addNewScenePlaceholder();
        $(story.Scenes).sort(compareScenes).each(function(index, scene) {
            scene.Order = index;
            addSceneToUI(scene);
        });

        $('#storySummary').val(story.Summary);
        $('#storySummary').change(function(){story.Summary = $('#storySummary').val();});
        $('#storyTitle').text(story.Title ? story.Title : '<Set title>');
        $('.title').click(function(event){editTitle(event.target)});
        $('#sceneSummary').change(function(){ story.Scenes[uiInfo.currentSceneIndex].Summary = $('#sceneSummary').val(); });
        $('#sceneProse').change(function(){ story.Scenes[uiInfo.currentSceneIndex].Prose = $('#sceneProse').val(); });
        $('#sceneArrangePanel').sortable({start: startDrag, stop: sort});
        shortcut.add("ctrl+a", function() {addSceneToCollection();});
    });
</script>

<div>
    <span id="storyTitle" class="title"/> <span class="titleInstructions">click to edit</span>
</div>

<div>
    <a href="javascript: toggleSummary()">Summary</a>
    <div id="summaryEditor" style="display:none">
        <textarea id="storySummary" rows="10" cols="50"></textarea>
    </div>
</div>

<div>
    <ul id="modeMenu">
        <li>Scene Arrange Mode
            <ul>
                <li><a href="javascript: showSceneEditor()">Scene Arrange Mode</a></li>
                <li><a href="javascript: $('.editPanel').selectFromGroup('#sceneEditPanel');">Scene Edit Mode</a></li>
            </ul>
        </li>
    </ul>
</div>

<div>
    <a href="javascript: save()">Save</a>
</div>

<br style="clear:both;" />

<div>
    <ul id="sceneArrangePanel" class="editPanel">
    </ul>
</div>

<div id="sceneEditPanel" class="editPanel" style="display:none">
    <div id="sceneSelectorSection">
        <span id="addSceneLink" class="sceneSelector"><a href="javascript: addSceneToCollection()">Add</a></span>
    </div>

    <div class="storyMenu" style="display:none">
        <a href="">Characters</a>
    </div>

    <br style="clear: both"/>

    <div id="sceneEditor" style="display:none">
        <div>
            <span id="sceneName" class="title"></span> <span class="titleInstructions">click to edit</span>
        </div>

        <div>
            <textarea id="sceneSummary" rows="10" cols="50">&lt;Write a summary of the scene&gt;</textarea>
        </div>

        <div><a href="">Prose</a> / <a href="">Panel</a></div>

        <div id="prosePanel">
            <textarea id="sceneProse" cols="50" rows="20">&lt;Write the scene&gt;</textarea>
        </div>
    </div>
</div>
